using System;
using System.Net.Mail;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Profile;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Membership;
using DotNetNuke.Services.Authentication;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Mail;
using DotNetNuke.UI.UserControls;

namespace Jfc.DnnMarketingTools.MemberInvite
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The RegisterInvited class is used to manage content
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// </history>
    /// -----------------------------------------------------------------------------
    partial class RegisterInvited : UserModuleBase
    {

        #region Private Members

        private string _InviteGuid = String.Empty;

        #endregion


        #region Event Handlers

        protected void Page_Init(System.Object sender, System.EventArgs e)
        {
            UserControl.ID = "User";


            UserControl.Visible = true;
            UserControl.ShowPassword = true;
            UserControl.FindControl("plWebsite").Visible = false;
            UserControl.FindControl("txtWebsite").Visible = false;
            UserControl.FindControl("plIM").Visible = false;
            UserControl.FindControl("txtIM").Visible = false;

            // Verify that the current user has access to this page
            if (PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration && Request.IsAuthenticated == false)
                Response.Redirect(Globals.NavigateURL("Access Denied"), true);

            /*
            lblRegisterHelp.Text = Localization.GetSystemMessage(PortalSettings, "MESSAGE_REGISTRATION_INSTRUCTIONS");

            switch (PortalSettings.UserRegistration)
            {
                case PortalRegistrationType.PrivateRegistration:
                    {
                        lblRegisterHelp.Text += Localization.GetString("PrivateMembership", Localization.SharedResourceFile);
                        break;
                    }
                case PortalRegistrationType.PublicRegistration:
                    {
                        lblRegisterHelp.Text += Localization.GetString("PublicMembership", Localization.SharedResourceFile);
                        break;
                    }
                case PortalRegistrationType.VerifiedRegistration:
                    {
                        lblRegisterHelp.Text += Localization.GetString("VerifiedMembership", Localization.SharedResourceFile);
                        break;
                    }
            }
            */
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                if (Request.IsAuthenticated)
                {
                    if (PortalSettings.UserTabId != -1)
                        Response.Redirect(Globals.NavigateURL(PortalSettings.UserTabId), true);
                    else
                        Response.Redirect(Globals.NavigateURL(PortalSettings.ActiveTab.TabID, "Profile", "UserID=" + UserInfo.UserID.ToString()), true);
                }

                //If this is the first visit to the page, bind the role data to the datalist
                if (!Page.IsPostBack)
                {
                    lblSuccess.Visible = false;
                    lblGeneralError.Visible = false;
                    lblError.Visible = false;

                    if (Request.QueryString["Invite"] != null)
                    {
                        _InviteGuid = Request.QueryString["Invite"];
                    }

                    MemberInviteInfo objMemberInvite = null;

                    if (!String.IsNullOrEmpty(_InviteGuid))
                    {
                        //get content
                        MemberInviteController objMemberInvites = new MemberInviteController();
                        objMemberInvite = objMemberInvites.GetMemberInviteByGuid(new Guid(_InviteGuid));
                    }

                    if (objMemberInvite == null)
                    {
                        Response.Redirect(Globals.NavigateURL(PortalSettings.HomeTabId), true);
                    }

                    //UserControl.LocalResourceFile = this.LocalResourceFile;

                    UserControl.FirstName = objMemberInvite.FirstName;
                    UserControl.UserName = objMemberInvite.FirstName;

                    if (objMemberInvite.LastName != null)
                    {
                        UserControl.LastName = objMemberInvite.LastName;
                        UserControl.UserName = objMemberInvite.FirstName + "." + objMemberInvite.LastName;
                    }

                    if (objMemberInvite.Email != null)
                        UserControl.Email = objMemberInvite.Email;

                    UserControl.FindControl("txtPassword").Focus();

                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            try
            {
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsValid())
                    CreateUser();
            }
            catch (Exception exc) //Module failed to load
            {
                lblGeneralError.Visible = true;
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected bool IsValid()
        {
            return true;

            /*
            Dim _IsValid As Boolean = True

            'Check Captcha Control
            If UseCaptcha Then
                _IsValid = ctlCaptcha.IsValid
            End If

            'Check User Editor
            If _IsValid Then
                _IsValid = UserEditor.IsValid
            End If

            'Check Password is valid
            If AddUser And ShowPassword Then
                Dim createStatus As UserCreateStatus = UserCreateStatus.AddUser
                If Not chkRandom.Checked Then
                    '1. Check Password and Confirm are the same
                    If txtPassword.Text <> txtConfirm.Text Then
                        createStatus = UserCreateStatus.PasswordMismatch
                    End If
                    '2. Check Password is Valid
                    If createStatus = UserCreateStatus.AddUser And Not UserController.ValidatePassword(txtPassword.Text) Then
                        createStatus = UserCreateStatus.InvalidPassword
                    End If
                    If createStatus = UserCreateStatus.AddUser Then
                        User.Membership.Password = txtPassword.Text
                    End If
                Else
                    'Generate a random password for the user
                    User.Membership.Password = UserController.GeneratePassword()
                End If

                'Check Question/Answer
                If createStatus = UserCreateStatus.AddUser And MembershipProviderConfig.RequiresQuestionAndAnswer Then
                    If String.IsNullOrEmpty(txtQuestion.Text) Then
                        'Invalid Question
                        createStatus = UserCreateStatus.InvalidQuestion
                    Else
                        User.Membership.PasswordQuestion = txtQuestion.Text
                    End If
                    If createStatus = UserCreateStatus.AddUser Then
                        If String.IsNullOrEmpty(txtAnswer.Text) Then
                            'Invalid Question
                            createStatus = UserCreateStatus.InvalidAnswer
                        Else
                            User.Membership.PasswordAnswer = txtAnswer.Text
                        End If
                    End If
                End If

                If createStatus <> UserCreateStatus.AddUser Then
                    _IsValid = False
                    valPassword.ErrorMessage = "<br/>" + UserController.GetUserCreateStatus(createStatus)
                    valPassword.IsValid = False
                End If

            End If

            Return _IsValid
            */
        }

        protected void CreateUser()
        {
            if (Request.QueryString["Invite"] != null)
            {
                _InviteGuid = Request.QueryString["Invite"];
            }

            UserInfo userInfo = new UserInfo();
            userInfo.Profile.InitialiseProfile(PortalId);

            userInfo.FirstName = UserControl.FirstName;
            userInfo.LastName = UserControl.LastName;
            userInfo.Username = UserControl.UserName;
            userInfo.Email = UserControl.Email;
            userInfo.DisplayName = UserControl.FirstName;
            //userInfo.FullName = 
            userInfo.IsSuperUser = false;
            userInfo.PortalID = PortalId;

            userInfo.Membership.Password = UserControl.Password;
            userInfo.Membership.LockedOut = false;

            if(PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration)
                userInfo.Membership.Approved = false;
            else
                userInfo.Membership.Approved = true;

            userInfo.Profile.IM = UserControl.IM;
            userInfo.Profile.Website = UserControl.Website;

            if (String.IsNullOrEmpty(UserInfo.Profile.GetPropertyValue("Biography")))
                userInfo.Profile.SetProfileProperty("Biography", "Invite " + _InviteGuid);
            
            UserCreateStatus status = UserController.CreateUser(ref userInfo);

            if (status != UserCreateStatus.Success)
            {
                lblError.Text = UserController.GetUserCreateStatus(status);
                lblError.Visible = true;

                return;
            }

            lblSuccess.Visible = true;

            if (!String.IsNullOrEmpty(_InviteGuid))
            {
                //get content
                MemberInviteController objMemberInvites = new MemberInviteController();
                MemberInviteInfo objMemberInvite = objMemberInvites.GetMemberInviteByGuid( new Guid(_InviteGuid));

                if (objMemberInvite != null)
                {
                    objMemberInvite.SetStatus(StatusType.Accepted);
                    objMemberInvites.UpdateMemberInvite(objMemberInvite);
                }
            }

            UserController.UserLogin(PortalId, userInfo, PortalSettings.PortalName, Request.UserHostAddress, false);
            Response.Redirect(Globals.NavigateURL(PortalSettings.HomeTabId), true);
        }
    }
}

